const path = require('path')
const EslintWebpackPlugin = require('eslint-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');

console.log(process.env.NODE_ENV);
// 获取环境变量
const isProcess = process.env.NODE_ENV === 'production'
// 返回处理cssloader方法
const getStyleLoaders = (pre)=>{
   return   [isProcess?MiniCssExtractPlugin.loader:'style-loader', "css-loader",
        // 处理css兼容性问题，
        // 配合package.json 中browserslist来指定兼容性
            {
                loader: 'postcss-loader',
                options: {
                    postcssOptions: {
                        plugins:["postcss-preset-env"]
                    }
                },
            },
            pre,
        ].filter(Boolean)
}
module.exports = {
    entry: './src/main.js',
    output: {
        path: isProcess?path.resolve(__dirname,'../dist') : undefined,
        filename: isProcess?'static/js/[name].[contenthash:10].js':'static/js/[name].js', //入口文件打包文件名
        chunkFilename: isProcess?'static/js/[name].[contenthash:10].chunk.js':'static/js/[name].chunk.js', // 非入口的chunk文件名
        assetModuleFilename: 'static/media/[name].[hash:10].[ext][query]', // 图片、字体等资源文件名
        clean: true,
    },
    module: {
        //处理css 
        rules: [{
            test: /\.css$/,
            use: getStyleLoaders(),

        },
        {
            test: /\.less$/,
            use: getStyleLoaders('less-loader'),// 处理less文件，需要安装less-loader插件

        },
        {
            test: /\.s[ac]ss$/,
            use: getStyleLoaders('sass-loader'),// 处理sass文件，需要安装sass-loader插件

        },
        
        {
            test: /\.styl$/,
            use:getStyleLoaders('stylus-loader'),

        },
        // 处理图片
        {
            test: /\.(png|jpe?g|gif|webp|svg)$/,
            type: 'asset',
            parser: {
                dataUrlCondition: {
                    maxSize: 10 * 1024 // 小于10kb的图片会被base64处理，减少网络请求，但是图片会变大
                }
            }
        },
        // 处理其他资源

        {
            test: /\.(woff2?|ttf)$/,
            type: 'asset/resource',
        },
        // 处理 代码检查，

        {
            test: /\.jsx?$/,
            include: path.resolve(__dirname, '../src'), // 指定检查的目录
            loader:'babel-loader',
            options:{
                cacheDirectory:true, // 开启babel缓存
                cacheCompression:false, // 缓存文件不要压缩
                plugins:[!isProcess&&'react-refresh/babel'].filter(Boolean) //激活js的HMR
            }
        }
    ]
    
    },
    // 处理html 
    plugins: [
        new EslintWebpackPlugin({
            context: path.resolve(__dirname, '../src'), // 指定检查的目录
            exclude: 'node_modules', // 排除检查的目录
            cache:true, // 开启缓存
            cacheLocation: path.resolve(__dirname, '../node_modules/.cache/.eslintcache'), // 缓存存放的位置
        }),
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, '../public/index.html'),
        }),
        isProcess&&new MiniCssExtractPlugin({
            filename:'static/css/[name].[contenthash:10].css',
            chunkFilename:'static/css/[name].[contenthash:10].chunk.css'
        }),
        // 复制文件
         new CopyPlugin({
            patterns: [
                {
                    from: path.resolve(__dirname, "../public"),
                    to: path.resolve(__dirname, "../dist"),
                    toType: "dir",
                    noErrorOnMissing: true, // 不生成错误
                    globOptions: {
                      // 忽略文件
                      ignore: ["**/index.html"],
                    },
                    info: {
                      // 跳过terser压缩js
                      minimized: true,
                    },
                  },
            
            ],
          }),
          !isProcess && new ReactRefreshWebpackPlugin() //开发模式下
    ].filter(Boolean),
    mode:isProcess?"production":"development",
    devtool:"source-map",
    optimization:{
        splitChunks:{
            chunks:"all",//
            cacheGroups:{
                // react文件单独打包
                react:{
                    test:/[\\/]node_modules[\\/]react(.*)?[\\/]/,
                    name:"chunk-react",
                    priority:40
                },
                // 组件库单独打包
                antd:{
                    test:/[\\/]node_modules[\\/]antd(.*)?[\\/]/,
                    name:"chunk-antd",
                    priority:30
                },
                // node_modules单独打包
                libs:{
                    test:/[\\/]node_modules[\\/]/,
                    name:"chunk-libs",
                    priority:20
                }
            }
        },
        runtimeChunk:{
            name:(entrypoint)=>`runtime~${entrypoint.name}.js`
        },
        // 压缩
        minimize:isProcess,
        minimizer:[
        // 压缩css
            new CssMinimizerWebpackPlugin(),
            // 压缩js
            new TerserWebpackPlugin(),
            //压缩图片
            new ImageMinimizerPlugin({
                minimizer: {
                  implementation: ImageMinimizerPlugin.imageminGenerate,
                  options: {
                    plugins: [
                      ["gifsicle", { interlaced: true }],
                      ["jpegtran", { progressive: true }],
                      ["optipng", { optimizationLevel: 5 }],
                      [
                        "svgo",
                        {
                          plugins: [
                            "preset-default",
                            "prefixIds",
                            {
                              name: "sortAttrs",
                              params: {
                                xmlnsOrder: "alphabetical",
                              },
                            },
                          ],
                        },
                      ],
                    ],
                  },
                },
              }),
        ]
    },
    // 自动补全文件扩展名
    resolve:{
        extensions:['.jsx','.js','.json'],
        // alias:{
        //     '@':path.resolve(__dirname, '../src'),
        //     'pages':path.resolve(__dirname, '../src/pages'),
        //     'components':path.resolve(__dirname, '../src/components'),
        // }
    },
    // 开启热模块替换
 // 开启热模块替换
 devServer:{
    host:"localhost",
    port:3000,
    open:true,
    hot:true,//开启HMR
    historyApiFallback:true,//解决路由刷新404问题
},
performance:false //关闭性能分析，加快打包速度


}